package com.linan.user.controller;

import com.linan.user.domain.User;
import com.linan.user.service.IUserService;
import com.linan.util.AjaxResult;
import com.linan.util.MD5Utils;
import com.linan.util.RedisUtils;
import com.linan.util.StrUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;
    @RequestMapping("/register")
    public AjaxResult register(@RequestBody Map<String,String> map) {
        String phone = map.get("phone");
        final String code = map.get("code");
        String key = "smsCode_register:"+phone;
        String codeFromRedis = RedisUtils.INSTANCE.get(key);
        System.out.println(codeFromRedis.split(":")[0]);
        if(StringUtils.isNotBlank(codeFromRedis)&&codeFromRedis.split(":")[0].equals(code)){
            final String salt = StrUtils.getComplexRandomString(10);
            User user = new User();
            user.setPhone(phone);
            user.setCreateTime(new Date());
            user.setUsername(map.get("username"));
            user.setPassword(MD5Utils.encrypByMd5(map.get("password")+salt));
            user.setSalt(salt);
            userService.save(user);
        }else{
            return new AjaxResult("验证码或手机号不正确");
        }
        return new AjaxResult();
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody  User user){
        User userinfo = userService.loadByUserName(user.getUsername());
        if(userinfo==null){
            return new AjaxResult("请输入正确的用户名和密码");
        }

        if(userinfo.getState()==0){
            return new AjaxResult("用户不能正常使用，请联系管理员");
        }

         String inputPWD = MD5Utils.encrypByMd5(user.getPassword() + userinfo.getSalt());
        if(!inputPWD.equals(userinfo.getPassword())){
            return new AjaxResult("密码错误");
        }
        String uToken = UUID.randomUUID().toString();
        RedisUtils.INSTANCE.set(uToken, JSONObject.toJSONString(userinfo), 30 * 60);
        HashMap<String, Object> map = new HashMap<>();
        map.put("uToken", uToken);
        map.put("user", userinfo);
        AjaxResult result = new AjaxResult();
        result.setData(map);
        return result;


    }
}
